package art.java.concurrency.chapter04;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="eric_zheng@lanzuo.com.cn">eric</a>
 * @version 1.0.0
 * Description: 线程的优先级，程序的正确性不能依赖线程的优先级高低。
 */
public class Priority {

    private static volatile boolean notStart = true;
    private static volatile boolean notEnd = true;

    public static void main(String[] args) throws InterruptedException {
        List<Job> jobs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
            Job job = new Job(priority);
            jobs.add(job);

            Thread thread = new Thread(job, "Thread:" + i);
            thread.setPriority(priority);
            thread.start();
        }

        notStart = false;
        TimeUnit.SECONDS.sleep(10);

        notEnd = false;
        for (Job job : jobs) {
            System.out.println("Job Priority:" + job.priority + ", Count: " + job.jobCount);
        }
    }

    static class Job implements Runnable {
        private int priority;

        private long jobCount;

        public Job(int priority) {
            this.priority = priority;
        }

        @Override
        public void run() {
            while (notStart) {
                Thread.yield();
            }
            while (notEnd) {
                Thread.yield();
                jobCount++;
            }
        }
    }

    /**
     * 线程的优先级并没有生效， 所以程序的正确性不能依赖线程的优先级高低
     *
     * Job Priority:1, Count: 88049575
     * Job Priority:1, Count: 85766029
     * Job Priority:1, Count: 86048623
     * Job Priority:1, Count: 87457661
     * Job Priority:1, Count: 88996511
     * Job Priority:10, Count: 85203514
     * Job Priority:10, Count: 85563882
     * Job Priority:10, Count: 89338895
     * Job Priority:10, Count: 86622738
     * Job Priority:10, Count: 86901278
     */

}
